package fun.tan90.device.sink.td.plugin;

import com.alibaba.druid.pool.DruidDataSource;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.datasource.FlexDataSource;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.event.EventBus;
import org.noear.solon.core.event.EventListener;

import javax.sql.DataSource;

@Slf4j
public class SinkTdPlugin implements Plugin {

    AppContext context;

    @Override
    public void start(AppContext context) {
        log.info("SinkTdPlugin start");
        this.context = context;
        //添加自己的配置文件
        context.cfg().loadAdd("sink-td.yml");
        //扫描自己的bean
        context.beanScan(SinkTdPlugin.class);
    }

    @Override
    public void stop() {
        log.info("SinkTdPlugin stop");
        //移除事件订阅
        context.beanForeach(bw -> {
            if (bw.raw() instanceof EventListener) {
                EventBus.unsubscribe(bw.raw());
            } else if (bw.raw() instanceof MybatisFlexBootstrap mybatisFlexBootstrap) {
                if (mybatisFlexBootstrap.getDataSource() instanceof FlexDataSource flexDataSource) {
                    for (DataSource dataSource : flexDataSource.getDataSourceMap().values()) {
                        if (dataSource instanceof DruidDataSource druidDataSource) {
                            druidDataSource.close();
                        }
                    }
                }
            }
        });
    }
}